import React from 'react';
import PropTypes from 'prop-types';
import { stripesConnect } from '@folio/stripes/core';
import { FormattedMessage, injectIntl } from 'react-intl';
import Form from './form';

class FormContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      operator: {}
    };
  }

  componentDidMount() {
    this.getFormData()

  }

  static manifest = Object.freeze({
    add: {
      type: 'okapi',
      path: 'party/notify_template',
      fetch: false
    },
    update: {
      type: 'okapi',
      path: 'party/notify_template/!{params.id}',
      fetch: false
    },
    one: {
      type: 'okapi',
      path: 'party/notify_template',
      clear: false,
      accumulate: true
    },
    uniquenessValidator: {
      type: 'okapi',
      path: 'party/notify_template',
      clear: false,
      fetch: false,
      accumulate: true
    }
  });

  static propTypes = {
    history: PropTypes.object,
    match: PropTypes.object,
    resources: PropTypes.object,
    mutator: PropTypes.shape({
      add: PropTypes.shape({
        POST: PropTypes.func.isRequired
      }),
      update: PropTypes.shape({
        PUT: PropTypes.func.isRequired
      }),
      validate: PropTypes.shape({
        reset: PropTypes.func.isRequired,
        GET: PropTypes.func.isRequired
      }).isRequired
    }).isRequired,
    dictionary: PropTypes.object,
    params:PropTypes.object,
  };

  makeFormData = (id, formData) => {
    const data = {
      id,
      ...formData
    };
    return data;
  };

  asyncValidateField = (type, notice) => {
    const {
      params,
      mutator,
      intl
    } = this.props;
    return new Promise((resolve, reject) => {
      const query = {
        jsonb: {}
      };
      query.jsonb.type = type;
      query.jsonb.notice = notice;
      query.jsonb.state = 1;
      mutator.uniquenessValidator.reset();

      return mutator.uniquenessValidator
        .GET({ params: { query: JSON.stringify(query) } })
        .then(result => {
          if (
            result.success &&
            result.data.length > 0 &&
            result.data[0].id !== params.id
          ) {
            const error = intl.formatMessage({
              id: 'ui-party.messageTemplate.data.save.error'
            });
            return reject(error);
          } else {
            return resolve();
          }
        });
    });
  };

  create = ({ requestPreferences, creds, ...formData }) => {
    const {
      intl,
      mutator,
      history
    } = this.props;
    const _this = this;
    const param = formData;
    param.state = 0;
    param.operator = this.state.operator;
    delete param.operator.addresses;
    delete param.operator.preferredContactTypeId;
    delete param.operator.servicePoints;
    delete param.operator.curServicePoint;
    delete param.operator.dateOfBirth;
    try {
      mutator.add
        .POST(param)
        .then(res => {
          if (res) {
            alert(intl.formatMessage({id:"ui-party.other.saved.successfully"}));
            _this.cancel(false);
          }
        })
        .catch(error => {
          alert(intl.formatMessage({id:"ui-party.other.saved.err"}));
          console.debug(error);
        });
    } catch (e) {
      alert(intl.formatMessage({id:"ui-party.other.saved.err"}));
      console.debug(e);
    }
  };

  update({ requestPreferences, ...formData }) {
    const {
      params,
      mutator,
      history,
        intl
    } = this.props;
    const _this = this;
    const id = params.id ? params.id : null;
    const data = this.makeFormData(id, formData);
    const param = data;
    param.operator = this.state.operator;
    param.state = 0;
    delete param.operator.addresses;
    delete param.operator.preferredContactTypeId;
    delete param.operator.servicePoints;
    delete param.operator.curServicePoint;
    delete param.operator.dateOfBirth;
    mutator.update.PUT(data).then(() => {
      alert(intl.formatMessage({id:"ui-party.other.saved.successfully"}));
      _this.cancel(false);
    });
  }

  getFormData() {
    const {
      resources,
      params,
      mutator
    } = this.props;
    const { currentUser } = this.props.okapi;

    if (!!params && !!params.id){

     mutator.one.GET({path:`party/notify_template/${params.id}`}).then((response)=>{
        this.setState({
          initValues:response,
          operator: currentUser,
        })
      }).catch(e=>console.debug(e))

    }else{
      this.setState({
        initValues:{ state: 1, operator: currentUser, }
      })
    }


  }

  cancel = (flag = true) => {
     const { removeTopMenu, matchPath } = this.props;
    removeTopMenu(matchPath, flag);
  };


  render() {
    const {
      params,
    } = this.props;

    const onSubmit = params.id
      ? record => this.update(record)
      : record => this.create(record);
    const dictionary = {
      notice:[
        { id: '', name: 'none', desc: 'ui-party.messageTemplate.data.notice.empty' },
        { id: 1, name: 'weixin', desc: 'ui-party.messageTemplate.data.notice.weixin' },
        { id: 2, name: 'sms', desc: 'ui-party.messageTemplate.data.notice.textMessage' },
        { id: 3, name: 'email', desc: 'ui-party.messageTemplate.data.notice.email' }
      ],
      type:[
        { id: '', name: 'none', desc: 'ui-party.messageTemplate.data.type.empty' },
        { id: 1, name: 'enrollSuccess', desc: 'ui-party.messageTemplate.data.type.enrollSuccess' },
        { id: 2, name: 'signInSuccess', desc: 'ui-party.messageTemplate.data.type.signInSuccess' },
        { id: 3, name: 'auditPass', desc: 'ui-party.messageTemplate.data.type.auditPass' },
        { id: 4, name: 'auditReject', desc: 'ui-party.messageTemplate.data.type.auditReject' }
      ],
      state:[
        // { id: '', name: 'none', desc: 'ui-party.messageTemplate.data.type.empty' },
        { id: 1, name: 'enable', desc: 'ui-party.messageTemplate.data.state.enable' },
        { id: 0, name: 'disable', desc: 'ui-party.messageTemplate.data.state.disable' }
      ]
    };
    return (
      <Form
        onSubmit={onSubmit}
        initialValues={this.state.initValues}
        uniquenessValidator={this.props.mutator.uniquenessValidator}
        dictionary={dictionary}
        exitFlag={this.state.exitFlag}
        toModel={this.props.toModel}
        cancel={this.cancel}
        removeTopMenu={this.props.removeTopMenu}
        form={this.props.name}
        {...this.props}
      />
    );
  }
}
export default injectIntl(stripesConnect(FormContainer));
